<template>
  <tn-navbar 
    :bottom-shadow="false"
    fixed
  >
    <text class="title">编辑车辆</text>
  </tn-navbar>
  <view class="container">
    <view class="form-container">
      <view class="form-item">
        <view class="form-header">
          <text class="form-label">车牌号码</text>
          <view class="new-energy-option">
            <text class="new-energy-text">新能源车牌</text>
            <switch 
              :checked="isNewEnergyVehicle"
              @change="handleNewEnergyChange"
              color="#1aad19"
              style="transform: scale(0.8);"
            />
          </view>
        </view>
        <view class="license-plate-container" @tap="openKeyboard">
          <!-- 车牌号码方格显示 -->
          <view class="plate-grid-container">
            <!-- 省份简称格子 -->
            <view class="plate-grid plate-grid-province" :class="{ 'active': keyboardValue.length === 0 }">
              <text class="plate-text">{{ keyboardValue[0] || '' }}</text>
            </view>
            <!-- 字母和数字格子 - 根据是否新能源显示6个或7个 -->
            <view 
              v-for="(_, index) in (isNewEnergyVehicle ? 7 : 6)" 
              :key="index + 1" 
              class="plate-grid" 
              :class="{ 'active': keyboardValue.length === index + 1 }"
            >
              <text class="plate-text">{{ keyboardValue[index + 1] || '' }}</text>
            </view>
          </view>
        </view>
        <text class="tip-text" v-if="!keyboardValue">点击输入车牌号码，通知时使用</text>
      </view>

      <view class="form-item">
        <text class="form-label">备注</text>
        <textarea
            class="form-textarea"
            placeholder="请输入备注信息（选填）"
            v-model="vehicleForm.remark"
        ></textarea>
      </view>

      <view class="form-item">
        <text class="form-label">默认留言</text>
        <textarea
          class="form-textarea message-textarea"
          placeholder="请输入默认留言，如：如需挪车请联系物业，谢谢配合"
          v-model="vehicleForm.message"
          maxlength="100"
        ></textarea>
        <text class="word-count">{{ vehicleForm.message.length }}/100</text>
        <text class="message-tip">此留言将显示在扫码页面，方便他人了解您的要求</text>
      </view>

      <view class="form-item">
        <view class="notification-header">
          <text class="form-label">自定义通知设置</text>
          <switch 
            :checked="vehicleForm.notification.enabled"
            @change="handleSwitchChange"
            color="#1aad19"
          />
        </view>
        
        <view v-if="vehicleForm.notification.enabled" class="webhook-container">
          <input
            class="webhook-input"
            type="text"
            v-model="vehicleForm.notification.webhookUrl"
            placeholder="请输入Webhook地址"
          />
          <text class="webhook-tip">当有人扫码时，系统会向该地址发送通知而不是全局webhook地址</text>
        </view>
      </view>
    </view>

    <view class="form-actions">
      <button class="cancel-btn" @tap="navigateBack">取消</button>
      <button class="submit-btn" @tap="handleSubmit">保存</button>
    </view>
  </view>

  <!-- 车牌号输入键盘 -->
  <TnKeyboard
      v-model="keyboardValue"
      v-model:show="showKeyboard"
      mode="car"
      :vibrate="false"
      @confirm="onKeyboardConfirm"
  />
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import TnKeyboard from '@/uni_modules/tuniaoui-vue3/components/keyboard/src/keyboard.vue'

// 获取页面参数
const vehicleId = ref('');
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  if (options.id) {
    vehicleId.value = options.id;
    getVehicleDetail();
  }
});

// 车辆表单数据
const vehicleForm = ref({
  licensePlate: '',
  remark: '',
  message: '',
  notification: {
    enabled: false,
    webhookUrl: ''
  }
});

// 键盘相关
const keyboardValue = ref('');
const showKeyboard = ref(false);
// 新能源车牌标志
const isNewEnergyVehicle = ref(false);

// 监听键盘值变化，根据是否新能源车牌限制最大长度
watch(keyboardValue, (newValue) => {
  const maxLength = isNewEnergyVehicle.value ? 8 : 7;
  if (newValue.length <= maxLength) {
    vehicleForm.value.licensePlate = newValue;
  } else {
    keyboardValue.value = newValue.slice(0, maxLength);
  }
});

// 处理新能源车牌开关变化
const handleNewEnergyChange = (e: any) => {
  isNewEnergyVehicle.value = e.detail.value;
  // 如果从新能源切换到普通车牌，且当前输入超过7位，则截断
  if (!isNewEnergyVehicle.value && keyboardValue.value.length > 7) {
    keyboardValue.value = keyboardValue.value.slice(0, 7);
    vehicleForm.value.licensePlate = keyboardValue.value;
  }
};

// 处理通知开关变化
const handleSwitchChange = (e: any) => {
  vehicleForm.value.notification.enabled = e.detail.value;
};

// 添加模拟数据
const mockVehicleDetails = {
  "10": {
    code: 200,
    msg: "success",
    data: {
      id: 10,
      instime: 1742056481,
      remark: "",
      qrcode_url: "https://pro-cdn.bugjianghu.com/nuogeche_qrcode/20250316/clIQvaSZ.png",
      itime: "2025-03-16",
      message: "请联系物业",
      webhook_url: "",
      notification_enabled: 0,
      licensePlate: "苏Y665557",
      moveCount: 0,
      notification: {
        enabled: 0,
        webhookUrl: ""
      }
    },
    timestamp: 1742878932
  },
  "9": {
    code: 200,
    msg: "success",
    data: {
      id: 9,
      instime: 1742051281,
      remark: "",
      qrcode_url: "https://pro-cdn.bugjianghu.com/nuogeche_qrcode/20250315/PO2behWt.png",
      itime: "2025-03-15",
      message: "",
      webhook_url: "",
      notification_enabled: 0,
      licensePlate: "沪U763618",
      moveCount: 0,
      notification: {
        enabled: 0,
        webhookUrl: ""
      }
    },
    timestamp: 1742878932
  },
  "8": {
    code: 200,
    msg: "success",
    data: {
      id: 8,
      instime: 1741888137,
      remark: "我的车",
      qrcode_url: "https://pro-cdn.bugjianghu.com/nuogeche_qrcode/20250313/VtIYKyVS.png",
      itime: "2025-03-14",
      message: "自己去联系物业",
      webhook_url: "",
      notification_enabled: 0,
      licensePlate: "辽YEUU4Y",
      moveCount: 0,
      notification: {
        enabled: 0,
        webhookUrl: ""
      }
    },
    timestamp: 1742878932
  }
};

// 获取车辆详情
const getVehicleDetail = async () => {
  try {
    // 使用模拟数据替代API调用
    setTimeout(() => {
      // 获取对应ID的模拟数据
      const mockData = mockVehicleDetails[vehicleId.value];
      if (mockData) {
        // 设置表单数据
        vehicleForm.value = mockData.data;
        keyboardValue.value = vehicleForm.value.licensePlate;
        
        // 根据车牌长度判断是否为新能源车牌
        isNewEnergyVehicle.value = vehicleForm.value.licensePlate.length > 7;
        
        // 设置通知开关状态
        vehicleForm.value.notification.enabled = !!vehicleForm.value.notification_enabled;
      } else {
        // 如果没有找到对应ID的数据，使用默认数据
        uni.showToast({
          title: '未找到车辆信息',
          icon: 'none'
        });
      }
    }, 500);
  } catch (error) {
    console.error('获取车辆详情失败:', error);
    uni.showToast({
      title: '获取车辆详情失败',
      icon: 'none'
    });
  }
};

// 打开键盘
const openKeyboard = () => {
  keyboardValue.value = vehicleForm.value.licensePlate;
  showKeyboard.value = true;
};

// 键盘确认
const onKeyboardConfirm = (value: string) => {
  showKeyboard.value = false;
};

// 导航返回
const navigateBack = () => {
  uni.navigateBack();
};

// 表单提交
const handleSubmit = async () => {
  // 表单验证
  if (!keyboardValue.value) {
    uni.showToast({
      title: '请输入车牌号码',
      icon: 'none'
    });
    return;
  }

  // 提交前确保车牌号同步
  vehicleForm.value.licensePlate = keyboardValue.value;

  // 如果启用通知但未填写webhook地址
  if (vehicleForm.value.notification.enabled && !vehicleForm.value.notification.webhookUrl) {
    uni.showToast({
      title: '请输入Webhook地址',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 使用模拟数据替代API调用
    const templates = uni.getStorageSync('subMessageTemplateList');
    if(templates){
      // 模拟订阅消息结果
      console.log('模拟订阅消息模板:', templates);
      
      // 模拟成功订阅
      setTimeout(() => {
        uni.showToast({
          title: '订阅成功',
          icon: 'success',
          duration: 1500
        });
      }, 300);
    }
  } catch (error) {
    console.error('订阅消息失败:', error);
  }
  
  // 提交表单
  uni.showLoading({
    title: '保存中...'
  });
  
  // 模拟API调用
  setTimeout(() => {
    // 更新模拟数据
    if (mockVehicleDetails[vehicleId.value]) {
      mockVehicleDetails[vehicleId.value].data = {
        ...mockVehicleDetails[vehicleId.value].data,
        licensePlate: vehicleForm.value.licensePlate,
        remark: vehicleForm.value.remark,
        message: vehicleForm.value.message,
        notification_enabled: vehicleForm.value.notification.enabled ? 1 : 0,
        webhook_url: vehicleForm.value.notification.webhookUrl,
        notification: {
          enabled: vehicleForm.value.notification.enabled ? 1 : 0,
          webhookUrl: vehicleForm.value.notification.webhookUrl
        },
        update_time: new Date().toISOString().replace('T', ' ').substring(0, 19)
      };
    }
    
    uni.hideLoading();
    uni.showToast({
      title: '保存成功',
      icon: 'success'
    });

    // 返回上一页
    setTimeout(() => {
      navigateBack();
    }, 1500);
  }, 1000);
};
</script>

<style>
/* 从 add.vue 复制的样式 */
.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.container {
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-container {
  background-color: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  padding: 40rpx 30rpx;
  margin-bottom: 40rpx;
}

.form-item {
  margin-bottom: 40rpx;
  display: flex;
  flex-direction: column;
}

.form-label {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: 500;
}

/* 修改表单头部样式，使标题和开关在同一行 */
.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.new-energy-option {
  display: flex;
  align-items: center;
}

.new-energy-text {
  font-size: 26rpx;
  color: #666;
  margin-right: 5rpx;
}

/* 车牌输入框样式 */
.license-plate-container {
  position: relative;
  width: 100%;
  height: 110rpx;
  border-radius: 12rpx;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
  box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.plate-grid-container {
  display: flex;
  width: 100%;
  height: 90rpx;
  justify-content: center;
}

.plate-grid {
  width: 70rpx; /* 稍微调小一点宽度，以适应8个格子 */
  height: 90rpx;
  border: 1rpx solid #ddd;
  margin: 0 4rpx; /* 减小间距 */
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.plate-grid-province {
  background-color: #1aad19;
  color: white;
  border: none;
}

.plate-grid.active {
  border-color: #1aad19;
  border-width: 2rpx;
  transform: scale(1.05);
  box-shadow: 0 4rpx 8rpx rgba(26, 173, 25, 0.2);
}

.plate-text {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.plate-grid-province .plate-text {
  color: white;
}

.tip-text {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
  text-align: center;
}

.form-textarea {
  width: 100%;
  height: 200rpx;
  border: 1rpx solid #eee;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #f8f8f8;
  box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40rpx;
  padding: 0 20rpx;
}

.cancel-btn, .submit-btn {
  width: 48%;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  border-radius: 45rpx;
  font-size: 32rpx;
  font-weight: bold;
  letter-spacing: 4rpx;
  transition: all 0.2s ease;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
  box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.1);
}

.submit-btn {
  background-color: #1aad19;
  color: white;
  box-shadow: 0 6rpx 12rpx rgba(26, 173, 25, 0.3);
}

.cancel-btn:active, .submit-btn:active {
  transform: scale(0.98);
  box-shadow: 0 3rpx 6rpx rgba(0, 0, 0, 0.1);
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.webhook-container {
  margin-top: 20rpx;
}

.webhook-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #eee;
  border-radius: 12rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #f8f8f8;
  box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.webhook-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
  display: block;
}

/* 添加留言相关样式 */
.message-textarea {
  width: 100%;
  height: 160rpx;
  border: 1rpx solid #eee;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #f8f8f8;
  box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 10rpx;
}

.word-count {
  font-size: 24rpx;
  color: #999;
  text-align: right;
  display: block;
  margin-bottom: 10rpx;
}

.message-tip {
  font-size: 24rpx;
  color: #999;
  display: block;
}
</style> 